import os
import socket
from langchain_openai import OpenAI
from langchain_community.callbacks import get_openai_callback
from tenacity import retry, stop_after_attempt, wait_exponential
import traceback

# 设置API密钥
os.environ["OPENAI_API_KEY"] = "sk-ThA0WI5NVgQ1xYUf8BriyRJfIqBWRvbV5rrzmAWBvdjxsnWP"


# 可选：配置代理（取消注释并替换为你的代理信息）
# os.environ["HTTP_PROXY"] = "http://username:password@proxy.example.com:8080"
# os.environ["HTTPS_PROXY"] = "http://username:password@proxy.example.com:8080"

# 可选：临时使用固定IP（不推荐长期使用）
# socket.getaddrinfo = lambda *args: [(socket.AF_INET, socket.SOCK_STREAM, 6, '', ('44.209.239.233', 443))]

# 带重试机制的LLM调用函数
@retry(
    stop=stop_after_attempt(5),
    wait=wait_exponential(multiplier=1, min=4, max=30),
    reraise=True  # 确保最终错误被抛出
)
def call_llm(prompt):
    print("尝试连接OpenAI API...")
    llm = OpenAI(
        model_name="text-davinci-003",
        temperature=0.3,
        request_timeout=120,
        max_tokens=100
    )
    return llm.invoke(prompt)


try:
    print("开始调用OpenAI API，请耐心等待...")
    with get_openai_callback() as cb:
        result = call_llm("给我讲一个笑话")
        print(f"API调用成功！结果如下：\n{result}")
        print(f"调用详情：{cb}")

except Exception as e:
    print(f"API调用失败: {str(e)}")
    print("\n网络诊断信息：")

    # 尝试ping OpenAI域名
    try:
        import subprocess

        ping_result = subprocess.run(
            ["ping", "-c", "3", "api.openai.com"],
            capture_output=True,
            text=True
        )
        print(ping_result.stdout)
    except Exception as ping_ex:
        print(f"无法执行ping测试: {ping_ex}")

    # 打印完整错误堆栈
    traceback.print_exc()